﻿using System;
using System.Web.Mvc;
using SlamCms.Common;
using SlamCms.Data;
using SlamCms.SharePointServices;
using SlamCms.Web;

namespace SlamCms.Areas._default.Controllers
{
	public class SharepointDocumentController : Controller
	{
		private readonly Lazy<SharePointDocumentService> _sharepointDocumentService;
		private readonly Lazy<SlamCmsContext> _slamCmsContext;

		public SharepointDocumentController(Lazy<SharePointDocumentService> sharepointDocumentService, Lazy<SlamCmsContext> slamCmsContext)
		{
			_sharepointDocumentService = sharepointDocumentService;
			_slamCmsContext = slamCmsContext;
		}

		[HttpGet]
		public ActionResult Index(string url)
		{
			// TODO output cache but smarter
			var fileData = this._sharepointDocumentService.Value.Retrieve(url);

			if (fileData == null)
				return this.NotFound();

			return this.FileData(fileData);
		}

		[HttpGet]
		public ActionResult Download(string contentItemId)
		{
			var contentItem = _slamCmsContext.Value.CreateQuery(QueryBuilderOptions.AllZones)
															.FilterContentItemId(contentItemId)
															.GetFirstOrDefault();

			if (contentItem == null)
				return this.NotFound();

			var sharepointRelativeUrl = Url.AdminRedirectorRelative("document", contentItem.PrimaryContentItemId, new { version = contentItem.IsDraft() ? "draft" : "live" });
			var status = contentItem.IsDraft() ? "draft" : "live";
			var localFileName = "ContentItems\\{0}-{1}.file".F(contentItem.PrimaryContentItemId, status);

			var fileData = _sharepointDocumentService.Value.Retrieve(sharepointRelativeUrl, localFileName);

			if (fileData == null)
				throw new Exception("There was a problem retrieving the file.");

			return this.FileData(fileData);
		}
	}
}